home *** CD-ROM | disk | FTP | other *** search
- /* eol-convert.c
- *
- * converts the EOL in TEXT files to the chosen system
- */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include "ctc.h"
-
- #define STRING_TERMINATOR ('\0')
- #define CR ((unsigned char) 0x0d)
- #define LF ((unsigned char) 0x0a)
-
- int process (FILE *path, char *EOL, char *buffer)
- {
- char *start, *ptr;
-
- start = buffer;
- for (ptr = buffer; *ptr; )
- switch (*ptr) {
- default:
- ptr++;
- break;
- case CR: /* MAC or DOS end of line has been found */
- *ptr = STRING_TERMINATOR;
- fprintf (path, "%s%s", start, EOL);
- ptr++;
- if (*ptr == LF) ptr++; /* skip the LF */
- start = ptr;
- break;
- case LF: /* UNIX end of line has been found */
- *ptr = STRING_TERMINATOR;
- fprintf (path, "%s%s", start, EOL);
- ptr++;
- start = ptr;
- break;
- }
- if (start < ptr) /* write the last line, maybe an EOL */
- fprintf (path, "%s", start);
- return 0;
- }
-
-
- void ConvertFile (char *thefile, int EOLmode)
- {
- FILE *path;
- long int length, qty;
- char *buffer, EOL[4];
- unsigned int i, j, k;
-
- switch (EOLmode) {
- case DOS: strcpy (EOL, "\r\n\0"); break;
- case MAC: strcpy (EOL, "\r\0"); break;
- case UNIX: strcpy (EOL, "\n\0"); break;
- default: return;
- }
- path = fopen (thefile, "rb");
- if (!path) return; /* could not open the file for read */
- /*
- * find the length of the file
- * and allocate a buffer for its contents
- */
- fseek (path, (long int) 0, SEEK_END);
- length = ftell (path);
- fseek (path, (long int) 0, SEEK_SET);
- buffer = (char *) malloc ((size_t) length+1);
- if (!buffer) return; /* not enough memory for the buffer */
- buffer[length] = STRING_TERMINATOR; /* just in case */
- /*
- * read the file into the buffer
- */
- qty = fread ( (void *) buffer, (size_t) length, (size_t) 1, path);
- /*
- * re-open the file for writing
- */
- freopen (thefile, "wb", path);
- if (!path) return; /* could not open the file for write */
- fseek (path, (long int) 0, SEEK_SET);
- /*
- * do the conversion of the EOL characters
- */
- process (path, EOL, buffer);
- fclose (path);
- free (buffer);
- }
-